package com.baize.baizeapp.test.sku

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.baize.baizeapp.R
import com.baize.baizeapp.utils.dip2px
import com.baize.baizeapp.utils.getHeightInPx
import com.baize.baizeapp.utils.getWidthInPx
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback
import com.google.android.material.bottomsheet.BottomSheetDialog

class LiveShoppingDialogUtils {
    var bottomSheetDialog: BottomSheetDialog? = null
    var layoutView: View? = null


    companion object {
        fun build(mContext: Activity): Builder {
            return Builder(mContext)
        }
    }

    class Builder(val activity: Activity) {
        var minHeight: Float = 0.5f//最小高度百分比
        var myStyle = R.style.bottomSheetDialog
        var bottomSheetDialogUtils = LiveShoppingDialogUtils()
        var bottomSheetBehavior: BottomSheetBehavior<View>? = null
        var product: LivebcProduct? = null
        var selectedLivebcProductSku: LivebcProductSku? = null
        var listener: OnClickProductBuyListener? = null
        var enforceClose = false
        fun setEnforceClose(enforceClose: Boolean?) : Builder{
            this.enforceClose = enforceClose ?: false
            return this
        }
        fun setLivingProduct(product: LivebcProduct?): Builder {
            this.product = product
            return this
        }

        fun setClickBuyListener(listener: OnClickProductBuyListener?): Builder {
            this.listener = listener
            return this
        }

        /**
         * 设置布局
         * @param layoutView View
         */
        fun setView(layoutId: Int): Builder {
            bottomSheetDialogUtils.layoutView =
                LayoutInflater.from(activity).inflate(layoutId, null)
            return this
        }

        fun setStyle(myStyle: Int): Builder {
            this.myStyle = myStyle
            return this
        }

        /**
         * 所占窗口百分比
         */
        fun setMinHeight(minHeight: Float): Builder {
            this.minHeight = minHeight
            return this
        }


        private fun updateProductBottomBuyView(
            liveProductToBuy: TextView?,
            text: String,
            isEnable: Boolean
        ) {
            if (enforceClose) {
                liveProductToBuy?.text = "关闭"
                liveProductToBuy?.isEnabled = true
            }else{
                liveProductToBuy?.text = text
                liveProductToBuy?.isEnabled = isEnable
            }
        }

        private fun updateProductImage(liveProductImage: ImageView?, imageUrl: String?) {
            liveProductImage?.let {
                Glide.with(activity).load(imageUrl).into(it)
            }
//            liveProductImage?.tag = imageUrl
        }

        fun show(): LiveShoppingDialogUtils {
            listener?.isShowLivingFloatDialog(true)
            bottomSheetDialogUtils.run {
                if (layoutView == null)
                    setView(R.layout.live_product_shopping_bottom_sheet)
                bottomSheetDialog = BottomSheetDialog(activity, myStyle)
                val closeBtn = layoutView?.findViewById<View>(R.id.live_shopping_dialog_close)
                val liveProductPrice = layoutView?.findViewById<TextView>(R.id.live_product_price)
                val liveProductStock = layoutView?.findViewById<TextView>(R.id.live_product_stock)
                val liveProductToBuy =
                    layoutView?.findViewById<TextView>(R.id.live_product_to_buy)
                val liveProductImage =
                    layoutView?.findViewById<ImageView>(R.id.live_product_image)
                val liveProductStyleLayout =
                    layoutView?.findViewById<LinearLayout>(R.id.live_product_style)
                liveProductImage?.setOnClickListener {
                    val imageUrl = liveProductImage?.tag as String
                    if (TextUtils.isEmpty(imageUrl)) {
                        return@setOnClickListener
                    }
                    var title = product?.title
                    Toast.makeText(activity,"图片详情 ${imageUrl}",Toast.LENGTH_SHORT).show()
                }
                updateViewInfo(
                    liveProductImage,
                    liveProductToBuy,
                    liveProductPrice,
                    liveProductStock
                )
                liveProductToBuy?.setOnClickListener {
                    if (enforceClose) {
                        bottomSheetDialog?.dismiss()
                        return@setOnClickListener
                    }
                    if (selectedLivebcProductSku != null) {
                        selectedLivebcProductSku?.let {
                            it.brand = product?.brand ?: ""
                            it.title = product?.title ?: ""
                            it.shipping_type = product?.shipping_type ?: "covered"
                            it.shipping_price = product?.shipping_price ?: 0.0
                            listener?.clickProductBuy(it)
                        }
                        listener?.isShowLivingFloatDialog(false)
                        bottomSheetDialog?.dismiss()
                    }
                }
                liveProductStyleLayout?.removeAllViews()
                val selectedMap = mutableMapOf<String, String>()
                var recyclerviewList = mutableListOf<HSFlexBoxLayout>()
                var adapterList = mutableListOf<DialogFlexAdapter>()
                product?.attributes?.forEachIndexed { index, livebcProductAttribute ->
                    val productStyleList =
                        product?.getAttributeValueUIData(index) ?: mutableListOf()
                    val view = View.inflate(activity, R.layout.live_product_style_dialog, null)
                    val liveProductStyleName =
                        view.findViewById<TextView>(R.id.live_product_style_name)
                    val layoutLiveProductRecyclerview =
                        view.findViewById<HSFlexBoxLayout>(R.id.layout_live_product_recyclerview)
                    layoutLiveProductRecyclerview?.removeAllViews()
                    recyclerviewList.add(layoutLiveProductRecyclerview)
                    liveProductStyleName.text = livebcProductAttribute.showDialogAttributeName()
                    val adapter =
                        DialogFlexAdapter(
                            productStyleList, activity, layoutLiveProductRecyclerview,
                            selectedMap, product,
                            object : OnClickItemClickListener {

                                override fun onItemSelectedAllClick(livebcProductSku: LivebcProductSku?) {
                                    if (livebcProductSku != null) {
                                        selectedLivebcProductSku = livebcProductSku
                                        updateProductImage(
                                            liveProductImage,
                                            if (!TextUtils.isEmpty(livebcProductSku.image_url)) {
                                                livebcProductSku.image_url
                                            } else {
                                                if ((product?.image_urls?.size ?: 0) > 0) {
                                                    product?.image_urls?.get(0) ?: ""
                                                } else {
                                                    ""
                                                }
                                            }
                                        )
                                        liveProductPrice?.text = livebcProductSku.showPrice()
                                        var isEnable = false
                                        if (livebcProductSku.stock > 0) {
                                            liveProductStock?.visibility = View.VISIBLE
                                            liveProductStock?.text =
                                                livebcProductSku.getProductStock()
                                            isEnable = true
                                        } else {
                                            liveProductStock?.visibility = View.INVISIBLE
                                        }
                                        updateProductBottomBuyView(
                                            liveProductToBuy,
                                            livebcProductSku.getProductCanbeBuy(),
                                            isEnable
                                        )
                                    } else {
                                        selectedLivebcProductSku = null
                                        updateProductBottomBuyView(liveProductToBuy, "已售罄", false)
                                    }
                                }

                                override fun onItemUnSelectedClick() {
                                    selectedLivebcProductSku = null
                                    updateViewInfo(
                                        liveProductImage,
                                        liveProductToBuy,
                                        liveProductPrice,
                                        liveProductStock
                                    )
                                }

                                override fun updateView(
                                    selectedMap: MutableMap<String, String>
                                ) {
                                    recyclerviewList.forEachIndexed { index, flexLabelLayout ->
                                        val updateDataUIInfo =
                                            product?.getAttributeValueUIData(
                                                index,
                                                selectedMap
                                            )
                                                ?: mutableListOf()
                                        val dialogAdapter = adapterList[index]
                                        dialogAdapter.productStyleList = updateDataUIInfo
                                        flexLabelLayout.removeAllViews()
                                        flexLabelLayout.setAdapter(dialogAdapter)
                                    }
                                }

                            })
                    adapterList.add(adapter)
                    layoutLiveProductRecyclerview?.setAdapter(adapter)
                    if (index != 0) {
                        val params = LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT
                        )
                        params.setMargins(0, activity.dip2px(20f), 0, 0)
                        liveProductStyleLayout?.addView(view, params)
                    } else {
                        liveProductStyleLayout?.addView(view)
                    }

                }
                closeBtn?.setOnClickListener {
                    bottomSheetDialog?.dismiss()
                    listener?.isShowLivingFloatDialog(false)
                }
                val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(
                    activity.getWidthInPx() - activity.dip2px(30f),
                    View.MeasureSpec.AT_MOST
                )
                val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(
                    0,
                    View.MeasureSpec.UNSPECIFIED
                )
                liveProductStyleLayout!!.measure(widthMeasureSpec, heightMeasureSpec)
                layoutView!!.measure(widthMeasureSpec, heightMeasureSpec)
                var measuredHeight =
                    layoutView!!.measuredHeight + liveProductStyleLayout.measuredHeight
                val maxHeight =
                    activity.getHeightInPx()//TODO 1. 高度
                if (measuredHeight > maxHeight) {
                    measuredHeight = maxHeight
                }
                bottomSheetDialog?.setContentView(
                    layoutView!!,
                    ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, measuredHeight)
                )
                bottomSheetDialog?.setOnCancelListener {
                    listener?.isShowLivingFloatDialog(false)
                }
                bottomSheetBehavior =
                    BottomSheetBehavior.from(layoutView?.parent as View)
                bottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
                bottomSheetBehavior?.addBottomSheetCallback(object : BottomSheetCallback() {
                    override fun onStateChanged(bottomSheet: View, newState: Int) {
                        if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                            bottomSheetDialog?.dismiss()
                            bottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
                            listener?.isShowLivingFloatDialog(false)
                        }
                    }

                    override fun onSlide(bottomSheet: View, slideOffset: Float) {
                    }

                })
                //设置透明背景
                bottomSheetDialog?.window?.findViewById<View>(R.id.design_bottom_sheet)
                    ?.setBackgroundResource(android.R.color.transparent)
                activity.window.setWindowAnimations(myStyle)//设置动画效果
                bottomSheetDialog?.show()
            }
            return bottomSheetDialogUtils
        }

        private fun updateViewInfo(
            liveProductImage: ImageView?,
            liveProductToBuy: TextView?,
            liveProductPrice: TextView?,
            liveProductStock: TextView?
        ) {
            if ((product?.image_urls?.size ?: 0) > 0) {
                updateProductImage(liveProductImage, product?.image_urls?.get(0) ?: "")
            }
            if (product?.getProductStock() == 0) {
                updateProductBottomBuyView(liveProductToBuy, "已售罄", false)
            } else {
                updateProductBottomBuyView(liveProductToBuy, "确定", false)
            }
            liveProductPrice?.text = product?.showMinToMaxPrice()
            liveProductStock?.visibility = View.INVISIBLE
        }

    }

    fun setCancelable() {
        bottomSheetDialog?.setCancelable(false);
        bottomSheetDialog?.setCanceledOnTouchOutside(false);
    }

    /**
     * 弹窗高度，
     * @return height
     */
    fun getPeekHeight(mContext: Context, minimumHeight: Float): Float {
        val windowManager = mContext
            .getSystemService(Context.WINDOW_SERVICE) as WindowManager
//        val peekHeight = mContext.resources.displayMetrics.heightPixels
        val peekHeight = windowManager.defaultDisplay.height
        //设置弹窗高度为屏幕高度的3/4
        return peekHeight * minimumHeight
    }
}

interface OnClickProductBuyListener {
    fun clickProductBuy(selectedLivebcProductSku: LivebcProductSku)
    fun clickProductImage(title: String?, imageList: ArrayList<String>, position: Int)
    fun isShowLivingFloatDialog(isHidden: Boolean){}
}


class DialogFlexAdapter(
    var productStyleList: MutableList<AttributeValueUI>,
    var mContext: Activity,
    var layoutLiveProductRecyclerview: HSFlexBoxLayout,
    var selectedMap: MutableMap<String, String>,
    var product: LivebcProduct?,
    var onClickItemClickListener: OnClickItemClickListener? = null
) : FlexBoxAdapter {

    override fun getItemCount(): Int {
        return productStyleList.size
    }

    override fun getView(position: Int): View {
        val attributeValueUI = productStyleList[position]
        val itemView = mContext.layoutInflater.inflate(
            R.layout.adapter_live_product_style_item,
            layoutLiveProductRecyclerview,
            false
        )

        val nameText =
            itemView.findViewById<TextView>(R.id.live_product_style_value_name)
        nameText?.text = attributeValueUI.getAttributeValue()

        if (attributeValueUI.isClickEnable()) {
            nameText?.isClickable = true
            nameText?.isEnabled = true
            if (attributeValueUI.hasClick()) {
                nameText?.setTextColor(Color.parseColor("#ffffff"))
                nameText?.setBackgroundResource(R.drawable.live_product_style_click)
            } else {
                nameText?.setTextColor(Color.parseColor("#333333"))
                nameText?.setBackgroundResource(R.drawable.live_product_style_normal)
            }
        } else {
            nameText?.setTextColor(Color.parseColor("#ffffff"))
            nameText?.setBackgroundResource(R.drawable.live_product_style_enable)
            nameText?.isClickable = false
            nameText?.isEnabled = false
        }
        nameText?.setOnClickListener {
            productStyleList.forEachIndexed { index, attributeValueUI ->
                if (index == position) {
                    attributeValueUI.isClick = !attributeValueUI.hasClick()
                    if (attributeValueUI.isClick) {
                        selectedMap[attributeValueUI.getAttributeName()] =
                            attributeValueUI.getAttributeValue()
                    } else {
                        selectedMap.remove(attributeValueUI.getAttributeName())
                    }
                } else {
                    attributeValueUI.isClick = false
                }
            }
            onClickItemClickListener?.updateView(selectedMap)
            if (selectedMap.size == (product?.attributes?.size ?: 0)) {
                val livebcProductSku = product?.getLivebcProductSku(selectedMap)
                onClickItemClickListener?.onItemSelectedAllClick(livebcProductSku)
            } else {
                onClickItemClickListener?.onItemUnSelectedClick()
            }
        }

        return itemView
    }

}

interface OnClickItemClickListener {
    fun onItemSelectedAllClick(livebcProductSku: LivebcProductSku?)
    fun onItemUnSelectedClick()
    fun updateView(selectedMap: MutableMap<String, String>)
}